import CURDHelper from '@/utils/CURDHelper'
import PageConfig from '@/utils/pageConfig'
import { getBtnCtr } from '@/utils/BtnControl'
import Query from '@/components/Query';
import Calendar from '@/components/Calendar';
import { isNumber } from '@/utils/validate';
import { VxeUI } from 'vxe-pc-ui';
import XEUtils from 'xe-utils';
import XLSX from 'xlsx';
export default {
  name: 'ProjectProcess',
  components: {
    Query, Calendar
  },
  data() {
    const gltxItemRender = {
      name: 'VxeSelect',
      props: {
        multiple: true,
      },
      options: []
    };
    const shyEditRender = {
      name: 'VxeSelect',
      props: {
        multiple: true,
      },
      options: [],
    }
    return {
      gltxItemRender,
      shyEditRender,
      componentSize: PageConfig.ComponentSize,
      duration: PageConfig.Duration,
      btnPromission: '',
      editModal: false,
      QueryConditions: [],
      BaseApiUrl: '/api/Xmglxmxx',
      XmxxlcUrl: '/api/Xmglxmxxlc',
      XmxxpcUrl: '/api/Xmglxmxxpc',
      editRow: undefined,
      CalendarView: false,
      ShyOptions: [],
      QueryConfig: [{
        title: '客户名称',
        field: 'khmc',
        type: 'input',
        value: '',
        placeholder: '请输入客户名称以查询',
      },{
        title: '合同号',
        field: 'erpbh',
        type: 'input',
        value: '',
        placeholder: '请输入合同号以查询',
      }, {
        title: '体系名称',
        field: 'khmc',
        type: 'input',
        value: '',
        placeholder: '请输入体系名称以查询',
      }, {
        title: '签单日期',
        field: 'htqdrq',
        type: 'daterange',
        date1: undefined,
        date2: undefined,
        placeholder: ''
      }, {
        title: '排程审核状态',
        field: 'pcshzt',
        type: 'select',
        value: 'N',
        placeholder: '',
        options: [
          { label: '未审核', value: 'N' },
          { label: '已审核', value: 'Y' }
        ]
      },],
      GridOptions: {
        id: 'ProjectScheduling_MainGrid',
        border: true,
        stripe: true,
        loading: false,
        size: PageConfig.ComponentSize,
        height: 700,
        columnConfig: {
          resizable: true
        },
        rowConfig: {
          isHover: true,
          resizable: true,
          isCurrent: true
        },
        checkboxConfig: {
          highlight: true,
          range: true
        },
        exportConfig: {
        },
        toolbarConfig: {
          custom: true,
          slots: {
            buttons: 'customButtons'
          },
          tools: [
            { code: 'calendar', icon: 'vxe-icon-table', circle: true }
          ]
        },
        customConfig: {
          mode: 'drawer',
          storage: true
        },
        columns: [
          { type: 'seq', width: 50, rowResize: true },
          { type: 'checkbox', width: 35 },
          { field: 'erpbh', title: '合同号', minWidth: 100, showOverflow: true },
          { field: 'khmc', title: '客户名称', minWidth: 120, showOverflow: true },
          { field: 'qdmc', title: '渠道名称', minWidth: 120, showOverflow: true },
          { field: 'txmc', title: '体系名称', minWidth: 120, showOverflow: true },
          { field: 'txgg', title: '体系规格', minWidth: 100, showOverflow: true },
          { field: 'rzbz', title: '体系版本', minWidth: 120, showOverflow: true },
          { field: 'lxr', title: '联系人', minWidth: 100, showOverflow: true },
          { field: 'lxdh', title: '联系人手机', minWidth: 100, showOverflow: true },
          { field: 'lxyx', title: '联系人邮箱', minWidth: 120, showOverflow: true },
          { field: 'pcxx', title: '排程信息', minWidth: 280, showOverflow: true, type: 'html' },
          { field: 'pcshzt', title: '排程审核状态', minWidth: 120, showOverflow: true, slots: { default: 'auditStatus' } },
          { field: 'pcshr', title: '排程审核人', minWidth: 100, showOverflow: true },
          { field: 'pcshsj', title: '排程审核时间', minWidth: 120, showOverflow: true },
          { field: 'sfdcs', title: '是否多场所', minWidth: 120, showOverflow: true },
          { field: 'dcslb', title: '多场所类别', minWidth: 120, showOverflow: true },
          // { field: 'zslb', title: '证书类别', minWidth: 120, showOverflow: true },
          // { field: 'zsh', title: '证书号', minWidth: 120, showOverflow: true },
          { field: 'zydm', title: '专业代码', minWidth: 120, showOverflow: true },
          { field: 'rzfw', title: '认证范围', minWidth: 100, showOverflow: true },
          { field: 'txrs', title: '体系人数', minWidth: 80, showOverflow: true },
          // {
          //   field: 'zsksrq', title: '证书开始日期', minWidth: 80, showOverflow: true,
          //   formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
          // },
          // {
          //   field: 'zsjsrq', title: '证书结束日期', minWidth: 80, showOverflow: true,
          //   formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
          // },
          { field: 'sxq', title: '省份', minWidth: 120, showOverflow: true },
          { field: 'htlx', title: '合同类型', minWidth: 120, showOverflow: true },
          { field: 'htdz', title: '合同地址', minWidth: 120, showOverflow: true },
          { field: 'shlx', title: '审核类型', minWidth: 100, showOverflow: true },
          { field: 'csje', title: '初审金额', minWidth: 80, showOverflow: true },
          { field: 'jsje', title: '监审金额', minWidth: 80, showOverflow: true },
          { field: 'htje', title: '合同金额', minWidth: 80, showOverflow: true },
          {
            field: 'htqdrq', title: '合同签订日期', minWidth: 80, showOverflow: true,
            formatter: ({ cellValue }) => XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
          },

          { field: 'createtime', title: '创建时间', width: 120, showOverflow: true },
          { field: 'createname', title: '创建人', width: 60, showOverflow: true },
          { field: 'updatetime', title: '更新时间', width: 150, showOverflow: true },
          { field: 'updatename', title: '更新人', width: 60, showOverflow: true },
          { field: 'operation', title: '操作', fixed: 'right', width: 120, slots: { default: 'operation' } },
        ],
        data: []
      },
      PagerConfig: {
        align: 'center',
        pageSize: 25,
        total: 0,
        currentPage: 1,
        pageSizes: [10, 25, 50, 100, 200],
      },
      ProcessOptions: [
      ],
      CalendarData: [],
      CurrMonth: '',
      ProInfo: [],
      CalendarCopyData:[]
    }
  },
  created() {
    // 动态头部按钮
    this.btnPromission = getBtnCtr(
      this.$route.path,
      this.$store.getters.userPermission
    )
    this.GetShyOptions();
  },
  methods: {
    handleQuery(e) {
      this.QueryConditions = e;
      this.DoQuery(e);
    },
    handlePageChange() {
      this.DoQuery(this.QueryConditions);
    },
    handleEditModalReset() {

    },
    handleChildCancel() {
      this.$refs.childgrid.clearEdit();
    },
    hasEditStatus(row) {
      return this.$refs.childgrid.isEditByRow(row);
    },
    handleChildSave(row) {
      row.id == 0 ? this.DoChildAdd(row) : this.DoChildEdit(row);
    },
    handleScheduling(row) {
      this.editRow = row;
      this.DoQueryDetail(row.id);
      this.editModal = true;
    },
    handleAudit(row) {
      if (row.pcshzt == 'Y') {
        VxeUI.modal.message({ content: '已审核的排程信息不能审核', status: 'error', duration: this.duration });
        return;
      }
      this.DoAudit(row);
    },
    handleAuditCancel(row) {
      if (row.pcshzt != 'Y') {
        VxeUI.modal.message({ content: '该排程信息未审核，无需反审', status: 'error', duration: this.duration });
        return;
      }
      this.DoAuditCancel(row);
    },
    handleToolbarToolClick({ code }) {
      if (code == 'calendar') {
        this.DoSetCurrentMonth();
      }
    },
    handleToolbarListClick({ code }) {
      if (code == 'list') {
        this.CalendarView = false;
      }
    },
    handleCalendarCellClick({ date }) {
      this.GetProjectInfo(date);
    },
    handleUpMonthClick() {
      this.DoSetUpMonth();
    },
    handleCurrMonthClick() {
      this.DoSetCurrentMonth();
    },
    handleNextMonthClick() {
      this.DoSetNextMonth();
    },
    handleCalendarViewChange(e) {
      if (e.viewType == 'day') {
        this.GetCalendarData();
      }
    },
    handleEditModalSubmit() {
      if (this.editRow.pcshzt == 'Y') {
        VxeUI.modal.message({ content: '已审核的排程信息不能修改', status: 'error', duration: this.duration });
        return;
      }
      this.DoSaveChild();
    },
    handleCardAdd(item) {
      item.data.push({
        id: 0 - item.data.length,
        xmid: item.xmid,
        xmlcid: item.id,
        rt: undefined,
        shyid: undefined,
        kssj: undefined,
        jssj: undefined,
      });
    },
    handleDeleteDetail(item, id) {
      //console.log(item, id)
      for (let i = item.data.length - 1; i >= 0; i--) {
        if (item.data[i].id == id) {
          item.data.splice(i, 1);
          break;
        }
      }
    },
    handleStartDateChange(itemModel) {
      if (itemModel.kssj) {
        let date = new Date(`${itemModel.kssj} 00:00:00`);
        let newJssj = date.setDate(date.getDate() + itemModel.rt - 0.0001);
        itemModel.jssj = XEUtils.toDateString(newJssj, 'yyyy-MM-dd');
      }
      //itemModel.jssj = itemModel.kssj.setDate(itemModel.rt);
    },
    GetShyOptions() {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [{
          column: 'isAuditer',
          content: '1',
          condition: '0'
        }],
        orderByConditions: []
      }
      CURDHelper.Query(request, '/api/Tusers')
        .then(res => {
          this.ShyOptions = [];
          res.data.map(item => {
            this.ShyOptions.push({
              label: item.userName,
              value: item.id
            })
          })
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    GetCalendarData() {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [
          { column: 'currMonth', content: this.CurrMonth, condition: '0' }
        ],
        orderByConditions: []
      }
      CURDHelper.Query(request, `${this.XmxxpcUrl}/GetCalendar`)
        .then(res => {
          this.CalendarData = res.data;
          this.CalendarCopyData=[];
          res.data.forEach(item => {
           this.CalendarCopyData.push({
            currMonth:item.currMonth,
            date:item.date,
            shy:item.shy
           }); 
          })
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })

    },
    GetProjectInfo(date) {
      let request = {
        isPaging: false,
        pageSize: 1,
        pageIndex: 1,
        queryConditions: [
          { column: 'currDay', content: date, condition: '0' }
        ],
        orderByConditions: []
      }
      CURDHelper.Query(request, `${this.XmxxpcUrl}/GetProInfo`)
        .then(res => {
          this.ProInfo = res.data;
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoSetUpMonth() {
      const currentDate = new Date(this.CurrMonth);
      currentDate.setMonth(currentDate.getMonth() - 1);
      this.CurrMonth = XEUtils.toDateString(currentDate, 'yyyy-MM');
      this.GetCalendarData();
    },
    DoSetCurrentMonth() {
      const currentDate = new Date();
      this.CurrMonth = XEUtils.toDateString(currentDate, 'yyyy-MM');
      this.GetCalendarData();
      this.CalendarView = true;
    },
    DoSetNextMonth() {
      const currentDate = new Date(this.CurrMonth);
      currentDate.setMonth(currentDate.getMonth() + 1);
      this.CurrMonth = XEUtils.toDateString(currentDate, 'yyyy-MM');
      this.GetCalendarData();
    },
    DoQuery(e) {
      if (e) {
        e.push({ column: 'shzt', content: 'Y', condition: '0' })
      } else {
        e = [{ column: 'shzt', content: 'Y', condition: '0' }]
      }
      let request = {
        isPaging: true,
        pageSize: this.PagerConfig.pageSize,
        pageIndex: this.PagerConfig.currentPage,
        queryConditions: e,
        orderByConditions: [{
          column: 't.id',
          condition: 'desc'
        }]
      }
      CURDHelper.Query(request, `${this.BaseApiUrl}/GetScheduling`)
        .then(res => {
          this.GridOptions.data = res.data;
          this.PagerConfig.total = res.totalNumber;
          this.editRow = undefined;
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoAudit(row) {
      let postData = {
        id: row.id,
        shzt: 'Y'
      }
      CURDHelper.EditWithConfirm('是否审核当前排程信息', postData, null, `${this.BaseApiUrl}/SchedulingAudit`)
        .then(res => {
          VxeUI.modal.message({ content: '审核数据成功', status: 'success', duration: this.duration });
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoAuditCancel(row) {
      let postData = {
        id: row.id
      }
      CURDHelper.EditWithConfirm('是否反审当前排程信息', postData, null, `${this.BaseApiUrl}/SchedulingAuditCancel`)
        .then(res => {
          VxeUI.modal.message({ content: '反审数据成功', status: 'success', duration: this.duration });
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoQueryDetail(xmid) {
      let request = {
        isPaging: true,
        pageSize: this.PagerConfig.pageSize,
        pageIndex: this.PagerConfig.currentPage,
        queryConditions: [{ column: 'xmid', content: xmid, condition: '0' },
        { column: 'sfxcsh', content: 'Y', condition: '0' }],
        orderByConditions: [{ column: 'lcxh', condition: 'asc' }]
      }
      CURDHelper.Query(request, `${this.XmxxlcUrl}/GetProcess`)
        .then(res => {
          this.ProcessOptions = res.data;
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    DoSaveChild() {
      let postData = []
      this.ProcessOptions.map(item1 => {
        item1.data.map(item => {
          if (item.shyid && item.rt && item.kssj && item.jssj) {
            if (item.kssj > item.jssj) {
              VxeUI.modal.message({ content: '开始时间不能大于结束时间', status: 'error', duration: this.duration });
              return;
            }
            var model = {
              xmid: item.xmid,
              xmlcid: item.xmlcid,
              shyid: item.shyid,
              rt: item.rt,
              kssj: item.kssj,
              jssj: item.jssj,
              shy: ''
            };
            this.ShyOptions.map(item2 => {
              if (item2.value == item.shyid) {
                model.shy = item2.label;
              }
            })
            postData.push(model)
          }
        })

      })
      if (postData.length == 0) {
        VxeUI.modal.message({ content: '请填写排程信息', status: 'error', duration: this.duration });
        return;
      }
      CURDHelper.Add(null, postData, `${this.XmxxpcUrl}`)
        .then(res => {
          VxeUI.modal.message({ content: '排程信息保存成功', status: 'success', duration: this.duration });
          this.editModal = false;
          this.DoQuery(this.QueryConditions);
        }).catch(err => {
          VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
        })
    },
    festivalCalendarMethod(params) {
      const { date, viewType } = params
      if (viewType === 'day') {
        const ymd = XEUtils.toDateString(date, 'yyyyMMdd')
        return this.calendarMaps[ymd] || { label: '' }
      }
    },
    handleImportScheduling() {
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet, { raw: false, dateNF: 'yyyy-MM-dd', cellDates: true });
          let erpbh = this.editRow.erpbh;
          let list = []
          resultJosn.find(function (value, index, arr) {
            if (value['合同号'] == erpbh) {
              list.push(value);
            }
          })

          if (!list || list.length == 0) {
            VxeUI.modal.message({ content: `未找到合同号为'${this.editRow.erpbh}'的排程信息`, status: 'error', duration: this.duration });
            return;
          }
          let schedulingList = []
          let shlx = this.editRow.shlx;
          if (this.editRow.shlx == '初认证') {
            list.find(function (value, index, arr) {
              if (value['审核性质'] == '一阶段' || value['审核性质'] == '二阶段') {
                schedulingList.push(value);
              }
            })
          } else {
            list.find(function (value, index, arr) {
              if (value['审核性质'] == shlx) {
                schedulingList.push(value);
              }
            })
          }
          if (!schedulingList || schedulingList.length == 0) {
            VxeUI.modal.message({ content: `未找到合同号为'${this.editRow.erpbh}'的'${shlx}'阶段的排程信息`, status: 'error', duration: this.duration });
            return;
          }
          this.ProcessOptions.forEach(p => {
            p.data = [];
            schedulingList.forEach(p1 => {
              console.log(p1)
              if (p.lcmc == p1['审核性质']) {
                let currshyid = 0;
                this.ShyOptions.forEach(p2 => {
                  if (p2.label == p1['审核员']) {
                    currshyid = p2.value;
                  }
                })
                let currKssj = p1['项目开始时间'].split('/');
                let currJssj = p1['项目结束时间'].split('/');
                let newScheduling = {
                  id: 0 - p.data.length - 1,
                  xmid: p.xmid,
                  xmlcid: p.id,
                  rt: p1['审核天数'],
                  shyid: currshyid,
                  kssj: new Date(`20${currKssj[2]}-${currKssj[0]}-${currKssj[1]}`),
                  jssj: new Date(`20${currJssj[2]}-${currJssj[0]}-${currJssj[1]}`)
                };
                p.data.push(newScheduling)
              }
            });
          })

        }
        reader.readAsArrayBuffer(e.file);
      })
    },
    handleBatchScheduling() {
      this.DoBatchScheduling();
    },
    DoBatchScheduling() {
      let selecedRows = this.$refs.maingrid.getCheckboxRecords(true);
      if (!selecedRows || selecedRows.length == 0) {
        VxeUI.modal.message({ content: '请选择需要批量导入排程的记录信息', status: 'error', duration: this.duration });
        return;
      }
      VxeUI.readFile().then((e) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const resultJosn = XLSX.utils.sheet_to_json(worksheet, { raw: false, dateNF: 'yyyy-MM-dd', cellDates: true });
          let postList = [];
          selecedRows.forEach(row => {
            let erpbh = row.erpbh;
            let list = []
            resultJosn.find(function (value, index, arr) {
              if (value['合同号'] == erpbh) {
                list.push(value);
              }
            })

            if (!list || list.length == 0) {
              VxeUI.modal.message({ content: `未找到合同号为'${this.editRow.erpbh}'的排程信息`, status: 'error', duration: this.duration });
              return;
            }
            let schedulingList = []
            let shlx = row.shlx;
            if (row.shlx == '初认证') {
              list.find(function (value, index, arr) {
                if (value['审核性质'] == '一阶段' || value['审核性质'] == '二阶段') {
                  schedulingList.push(value);
                }
              })
            } else {
              list.find(function (value, index, arr) {
                if (value['审核性质'] == shlx) {
                  schedulingList.push(value);
                }
              })
            }
            if (!schedulingList || schedulingList.length == 0) {
              VxeUI.modal.message({ content: `未找到合同号为'${row.erpbh}'的'${shlx}'阶段的排程信息`, status: 'error', duration: this.duration });
              return;
            }
            schedulingList.forEach(p1 => {
              let currshyid = 0;
              this.ShyOptions.forEach(p2 => {
                if (p2.label == p1['审核员']) {
                  currshyid = p2.value;
                }
              })
              let currKssj = p1['项目开始时间'].split('/');
              let currJssj = p1['项目结束时间'].split('/');
              let newScheduling = {
                id: 0,
                xmid: row.id,
                xmlcid: 0,
                rt: p1['审核天数'],
                shyid: currshyid,
                shy:p1['审核员'],
                lcmc: p1['审核性质'],
                kssj: `20${currKssj[2]}-${currKssj[0]}-${currKssj[1]}`,
                jssj: `20${currJssj[2]}-${currJssj[0]}-${currJssj[1]}`
              };
              postList.push(newScheduling);
            })

          });
          
          if (!postList || postList.length == 0) {
            VxeUI.modal.message({ content: '未找到排程信息', status: 'error', duration: this.duration });
            return;
          }
          CURDHelper.Add(null, postList, `${this.XmxxpcUrl}`)
            .then(res => {
              VxeUI.modal.message({ content: '排程信息导入成功', status: 'success', duration: this.duration });
              this.DoQuery(this.QueryConditions);
            }).catch(err => {
              VxeUI.modal.message({ content: `${err}`, status: 'error', duration: this.duration })
            })
        }
        reader.readAsArrayBuffer(e.file);
      })
    }
  }
}
